// pages/myOrder/myOrder.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navData: [{
        name: '全部订单',
        type: ''
      },
      {
        name: '待付款',
        type: 'WAITPAY'
      },
      {
        name: '待发货',
        type: 'WAITSEND'
      },
      {
        name: '待收货',
        type: 'WAITRECEIVE'
      },
      {
        name: '已完成',
        type: 'FINISH'
      }
    ],
    page: 1,
    isEnd: false,
    currentData: 0,
    receiving: true,
    orders: [],
    reasons: [
      '订单不能及时送达',
      '操作有误（商品、地址等选错）',
      '重复下单/误下单',
      '其他渠道价格更低',
      '该商品降价了',
      '不想买了'
    ],
    submit: 1,
    showModal: false,
    concent_list: ['微信支付', '会员卡支付'],
    curindex: 0,
    concent_monry: '',
    concent_sn: '',
    userInfoAuthorization: true,
    canIUseGetUserProfile: false,
  },

  //点击列表按钮
  navClick(e) {
    const that = this;
    if (e.currentTarget.dataset.currentdata != that.data.currentData) {
      that.setData({
        isEnd: false,
        page: 1
      })
    }
    that.setData({
      currentData: e.currentTarget.dataset.currentdata,
    })
    that.getOrderList();
  },

  //立即评价
  toEvaluate() {
    wx.navigateTo({
      url: '/page/detail/pages/myComments/myComments?index=1',
    })
  },

  doPay(e) { //立即支付
    const that = this;
    let submit = that.data.submit;
    if (submit == 1) {
      submit += 1;
      that.setData({
        submit: submit
      })
      setTimeout(() => {
        that.setData({
          submit: 1
        })
      }, 2000)
      let money = that.data.concent_monry;
      let sn = that.data.concent_sn;
      let json = {
        token: app.globalData.token,
        trade_type: "JSAPI",
        master_order_sn: sn,
        account: money
      }
      let jsonData = app.utils.getSignData(json);

      if (that.data.curindex == 1) {
        app.utils.post(app.api.reqUrls.carddoPay, jsonData).then(res => {
          if (res.status == 1) {
            wx.showToast({
              title: '支付成功',
              icon: "none"
            })
            that.getOrderList();
            app.getInfo(app.globalData.token)
          } else if (res.status == -1001) {
            wx.showModal({
              title: '温馨提示',
              content: '您还没有可使用的会员卡，是否去绑卡？',
              confirmText: '去绑卡',
              success: function (res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: -1,
                    success() {
                      wx.navigateTo({
                        url: `/page/details/pages/cardHolder/cardHolder?where=1`,
                      })
                    }
                  })
                } else if (res.cancel) {

                }
              }
            })
          } else if (res.status == -1002) {
            wx.showModal({
              title: '温馨提示',
              content: '会员卡余额不足，是否去充值？',
              confirmText: '去充值',
              success: function (shres) {
                if (shres.confirm) {
                  wx.navigateBack({
                    delta: -1,
                    success() {
                      wx.navigateTo({
                        url: '/page/details/pages/cardRecharge/cardRecharge?factamount=' + res.result.factamount,
                      })
                    }
                  })
                } else if (shres.cancel) {

                }
              }
            })
          } else {
            throw res.msg
          }
        }).catch(err => {
          app.showInfo(err.toString())
        })
      } else {
        app.utils.post(app.api.reqUrls.doPay, jsonData).then(res => {
          if (res.status == 1) {
            console.log("支付信息：", res.result)
            wx.requestPayment({ // 调取支付
              timeStamp: res.result.timeStamp.toString(),
              nonceStr: res.result.nonceStr,
              package: res.result.package,
              signType: res.result.signType,
              paySign: res.result.sign,
              success(res) {
                if (res.errMsg == "requestPayment:ok") {
                  that.getOrderList();
                  app.getInfo(app.globalData.token)
                } else {
                  throw res.errMsg;
                }
              },
              fail(res) {
                console.log(res)
              }
            })

          } else {
            throw res.msg
          }
        }).catch(err => {
          app.showInfo(err.toString())
        })
      }
    }
  },

  toGoodsDetail(e) {
    const that = this;
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/page/detail/pages/details/details?id=${id}`,
    })
  },
  //复制单号
  invoiceBtn(e){
    const that = this;
    let num = e.currentTarget.dataset.num;
    wx.setClipboardData({
      data: num,
      success (res) {
        wx.getClipboardData({
          success (res) {
            console.log(res.data) // data
            wx.showToast({
              title: '复制成功',
              icon: 'none',
              duration: 2000
            })
          }
          
        })
      }
    })

  },
  // 去申请售后
  toAfterSale(e) {
    console.log(e)
    wx.navigateTo({
      url: `/page/detail/pages/applyAfterSale/applyAfterSale?orderid=${e.currentTarget.dataset.orderid}&order_sn=${e.currentTarget.dataset.order_sn}`
    })
  },


  // 取消订单
  cancelOrder(e) {
    const that = this;
    let index = e.currentTarget.dataset.index;
    if (that.data.orders[index].order_status_detail == "待支付") {
      let json = {
        token: app.globalData.token,
        order_id_sn: that.data.orders[index].order_id + '=' + that.data.orders[index].master_order_sn
      }
      let jsonData = app.utils.getSignData(json);

      wx.showModal({
        content: '是否取消该订单',
        confirmText: '确定',
        confirmColor: '#ff5151',
        success(e) {
          if (e.confirm) {
            app.utils.post(app.api.reqUrls.cancelOrder, jsonData).then(res => {
              if (res.status == 1) {
                app.showInfo(res.msg)
                that.getOrderList();
              } else {
                throw res.msg
              }
            }).catch(err => {
              app.showInfo(err.toString())
            })
          }
        }
      })
    } else {

      wx.showActionSheet({
        itemList: that.data.reasons,
        success(res) {
          let json = {
            token: app.globalData.token,
            order_id: that.data.orders[index].order_id,
            consignee: that.data.orders[index].children[0].consignee,
            mobile: that.data.orders[index].children[0].mobile,
            user_note: that.data.reasons[res.tapIndex],
            is_json: 1
          }
          let jsonData = app.utils.getSignData(json);

          wx.showModal({
            content: '是否取消该订单',
            confirmText: '确定',
            confirmColor: '#ff5151',
            success(e) {
              if (e.confirm) {
                that.setData({
                  hiddenLoading: false
                })
                app.utils.post(app.api.reqUrls.cancelPaidOrder, jsonData).then(res => {
                  console.log(res)
                  that.setData({
                    hiddenLoading: true
                  })
                  if (res.status == 1) {
                    app.showInfo(res.msg);
                    that.getOrderList();
                  } else {
                    throw res.msg
                  }
                }).catch(err => {
                  app.showInfo(err.toString());
                  that.setData({
                    hiddenLoading: true
                  })
                })
              }
            }
          })
        },
        fail(res) {
          console.log(res.errMsg)
        }
      })
    }
  },

  toLogistics(e) { // 查看物流
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/page/detail/pages/logistics/logistics?id=${id}`,
    })
  },
  //确认收货
  orderConfirm(e) {
    const that = this;
    let id = e.currentTarget.dataset.id;
    let json = {
      token: app.globalData.token,
      order_id: id
    }
    let jsonData = app.utils.getSignData(json)
    that.setData({
      hiddenLoading: false
    })
    wx.showModal({
      content: '是否确认收货',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(e) {
        if (e.confirm) {
          app.utils.post(app.api.reqUrls.orderConfirm, jsonData).then(res => {
            that.setData({
              hiddenLoading: true
            })
            console.log(res)
            if (res.status == 1) {
              that.getOrderList();
              // wx.navigateTo({
              //   url: '/page/detail/pages/myComments/myComments?index=0',
              // })
            } else {
              throw res.msg
            }
          }).catch(err => {
            app.showInfo(err.toString());
            that.setData({
              hiddenLoading: true
            })
          })
        } else {
          that.setData({
            hiddenLoading: true
          })
        }
      },
      fail() {
        that.setData({
          hiddenLoading: true
        })
      }
    })
  },
  // 订单详情
  toDetail(e) {
    const that = this;
    let sn = e.currentTarget.dataset.sn;
    let id = e.currentTarget.dataset.id;
    let storeid = e.currentTarget.dataset.storeid;
    wx.navigateTo({
      url: `/page/detail/pages/orderDetails/orderDetails?sn=${sn}&id=${id}&store_id=${storeid}`,
    })
  },

  // 再来一单
  toBuyAgain(e) {
    const that = this;
    let json = {
      token: app.globalData.token,
      order_id_sn: e.currentTarget.dataset.id + '=' + e.currentTarget.dataset.order_sn
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.another_order, jsonData).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        wx.showModal({
          content: res.msg.toString(),
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {
            if (e.confirm) {
              wx.switchTab({
                url: '/page/tabBar/cart/cart',
              })
            }
          }
        })
      } else if (res.status == 0) {
        app.showInfo(res.msg.toString())
      } else {
        throw res.msg
      }
    }).catch(err => {
      if (res.status != undefined) {
        app.showInfo(err.toString());
      } else {
        console.log('服务器错误')
      }
    })
  },

  getOrderList() {
    const that = this;
    let json = {
      token: app.globalData.token,
      type: that.data.navData[that.data.currentData].type || '',
      p: 1
    }
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.getOrderList, app.utils.getSignData(json)).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        // console.log(res.result)
        if (res.result != null && res.result != []) {
          res.result.forEach(item => {
            if (item.children && item.children.length >= 2) {
              item.phonestate = 0;
              item.doublephoone = [];
              item.children.forEach(items => {
                if (items.store.store_type == 1) {
                  item.doublephoone.push('客服：' + items.store.store_phone);
                }
                if (items.store.store_type == 0) {
                  item.doublephoone.push('客服：' + items.store.store_phone);
                  item.store_newid = items.store.store_id;
                }
                if (items.store.store_type == 2) {
                  item.doublephoone.push('客服：' + items.store.store_phone);
                  item.store_newid = items.store.store_id;
                }
              })
            } else {
              if (item.children) {
                item.children.forEach(items => {
                  if (items.store.store_type == 1) {
                    item.phonestate = 1;
                    item.crdphone = items.store.store_phone;
                    item.store_newid = 0;
                  } else if (items.store.store_type == 0) {
                    item.phonestate = 2;
                    item.jrdphone = items.store.store_phone;
                    item.store_newid = items.store.store_id;
                  } else if (items.store.store_type == 2) {
                    item.phonestate = 3;
                    item.qiyephone = items.store.store_phone;
                    item.store_newid = items.store.store_id;
                  }
                })
              }

            }
            if (item.children) {
              item.children.forEach(item => {
                app.getImg(item.order_goods);
                item.count_goods = item.order_goods.length
              })
            }
          })
        }
        that.setData({
          orders: res.result
        })
      } else {
        throw res.msg
      }
    }).catch(err => {
      app.showInfo(err.toString())
      that.setData({
        hiddenLoading: true
      })
    })
  },



  getMoreOrderList() {
    const that = this;
    if (that.data.isEnd) {
      return
    }
    let json = {
      token: app.globalData.token,
      type: that.data.navData[that.data.currentData].type || '',
      p: that.data.page + 1
    }
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.getOrderList, app.utils.getSignData(json)).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        if (res.result != null && res.result != '') {
          res.result.forEach(item => {
            if (item.children && item.children.length >= 2) {
              item.phonestate = 0;
              item.doublephoone = [];
              item.children.forEach(items => {
                if (items.store.store_type == 1) {
                  item.doublephoone.push('客服：' + items.store.store_phone);
                }
                if (items.store.store_type == 0) {
                  item.doublephoone.push('客服：' + items.store.store_phone);
                  item.store_newid = items.store.store_id;
                }
                if (items.store.store_type == 2) {
                  item.doublephoone.push('客服：' + items.store.store_phone);
                  item.store_newid = items.store.store_id;
                }
              })
            } else {
              if (item.children) {
                item.children.forEach(items => {
                  if (items.store.store_type == 1) {
                    item.phonestate = 1;
                    item.crdphone = items.store.store_phone;
                    item.store_newid = 0;
                  } else if (items.store.store_type == 0) {
                    item.phonestate = 2;
                    item.jrdphone = items.store.store_phone;
                    item.store_newid = items.store.store_id;
                  } else if (items.store.store_type == 2) {
                    item.phonestate = 3;
                    item.qiyephone = items.store.store_phone;
                    item.store_newid = items.store.store_id;
                  }
                })
              }

            }
            if (item.children) {
              item.children.forEach(item => {
                app.getImg(item.order_goods);
                item.count_goods = item.order_goods.length
              })
            }
          })
          that.setData({
            orders: [...that.data.orders, ...res.result],
            page: that.data.page + 1
          })
        } else {
          that.setData({
            isEnd: true
          })
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
            duration: 1000
          })
        }
      } else {
        throw res.msg
      }
    }).catch(err => {
      app.showInfo(err.toString())
      that.setData({
        hiddenLoading: true
      })
    })
  },

  //联系客服
  servicePhone(e) {
    if (e.currentTarget.dataset.tel) {
      wx.makePhoneCall({
        phoneNumber: e.currentTarget.dataset.tel //仅为示例，并非真实的电话号码
      })
    } else {
      wx.showToast({
        title: '当前店铺没有留下联系方式',
        icon: "none"
      })
    }
  },
  //联系客服
  popSelect: function (e) {

    wx.showActionSheet({
      itemList: e.currentTarget.dataset.tel,
      success: function (res) {
        console.log(res.tapIndex);
        var str = e.currentTarget.dataset.tel[res.tapIndex];
        var str_new = str.substring(6, str.length) //取电话字符
        console.log(str_new);
        wx.makePhoneCall({
          phoneNumber: str_new //仅为示例，并非真实的电话号码
        })
      }
    })
  },

  getUserProfile(e) {
    const that = this;
    if (this.data.canIUseGetUserProfile) {
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log("logwxsucess", res);
          that.doLogin(e, res.userInfo);
        },
        fail: res => {
          console.log("logwxloginres", res);
          wx.hideLoading();
        }
      });
    } else {
      that.doLogin(e);
    }
  },

  doLogin(e, proFileUserInfo = null) { //旧的登陆代码
    const that = this;
    //原来的登陆代码逻辑，在旧的getUserInfo代码处新增判断：
    wx.getUserInfo({
      success: function (res) {
        /* begin 下面3行是新增的判断，代表userInfo已经通过wx.getUserProfile获取过获取过*/
        if (proFileUserInfo) {
          res.userInfo = proFileUserInfo;
        }
        let json = {
          oauth: "miniapp",
          nickname: res.userInfo.nickName,
          head_pic: res.userInfo.avatarUrl,
          sex: res.userInfo.gender,
          versionCode: app.globalData.systemInfo.SDKVersion,
          code: that.data.code,
          iv: res.iv,
          encryptedData: res.encryptedData,
          signature: res.signature
        }

        let jsonData = app.utils.getSignData(json); // 添加签名

        that.setData({
          hiddenLoading: false
        })
        app.utils.post(app.api.reqUrls.login, jsonData).then(res => {
          that.setData({
            hiddenLoading: true
          })
          if (res == 999) {
            return
          }
          if (res.status == 1) {
            app.globalData.isfirstnewuser = true;
            app.globalData.userInfo = res.result;
            app.globalData.userInfoAuthorization = true;
            that.setData({
              userInfo: res.result,
              userInfoAuthorization: true
            })
            wx.setStorageSync("token", res.result.token);
            wx.setStorageSync("userInfo", res.result);
            app.globalData.token = res.result.token;
            app.globalData.userInfo = res.result;

            that.getOrderList();

          } else {
            throw res.msg
          }
        }).catch(err => {
          if (err != undefined) {
            app.showInfo(err.toString())
          } else {
            console.log('服务器错误')
          }
          that.setData({
            hiddenLoading: true
          })
        })

        /* end */
      }
    });

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    if (options.where) {
      that.setData({
        currentData: options.where
      })
    }
  },

  onShow() {
    const that = this;
    app.utils.login().then(res => {
      that.setData({
        code: res.code
      })
    })
    that.setData({
      isEnd: false,
      page: 1,
      userInfoAuthorization: app.globalData.userInfoAuthorization,
    })
    if (that.data.userInfoAuthorization) {
      that.getOrderList();
    } else {
      wx.nextTick(() => {
        that.setData({
          hiddenLoading: true,
        })
        wx.stopPullDownRefresh()
      })
    }
    //数据统计
    app.statistics("page/detail/pages/myOrder/myOrder", "我的订单")
  },

  onReachBottom() {
    const that = this;
    that.getMoreOrderList();
  },
  //立即付款
  submitOrdershow(e) {
    const that = this
    let money = e.currentTarget.dataset.money;
    let sn = e.currentTarget.dataset.sn;

    let json = {
      token: app.globalData.token,
      trade_type: "JSAPI",
      master_order_sn: sn,
      account: money
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.doPay, jsonData).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        let preOrderId = res.result.pre_order
        let merchantId = res.result.ls_merchant_id
        let opAppId = res.result.open_appid
        wx.openEmbeddedMiniProgram({
          appId: opAppId, // 你要打开的小程序appid
          extraData: { //给B小程序传的参数
            autoPay: 1,
          },
          path: `pages/plugin/pay?preOrderId=${preOrderId}&merchantId=${merchantId}`, // 打开的页面路径，如果为空则打开首页
          envVersion: 'release', // 要打开的小程序版本 develop 开发版 trial 体验版 release 正式版
          success(resData) {
            console.log(resData, 11111)
            // 打开成功

            var listener = (props) => {
              console.log(props, 111)
              console.log(props.referrerInfo, 222)
              console.log(props.referrerInfo.extraData, 333)
              if (!props.referrerInfo.hasOwnProperty('extraData')) {
                console.log('错误')
                that.getOrderList();
                console.log(1234)
                if (listener) {
                  console.log(4567)
                  wx.offAppShow(listener)
                }
              }
              if (props.referrerInfo.extraData.payStatus === '0') {
                console.log('支付失败')
                //支付失败
                //.....
                wx.showModal({
                  content: '付款失败',
                  showCancel: false,
                  confirmText: '我知道了',
                  confirmColor: '#ff5151',
                  success(e) {
                    if (e.confirm) {
                      that.getOrderList();
                    }
                  }
                })
              }
              if (props.referrerInfo.extraData.payStatus === '1') {
                console.log('支付成功')
                //支付成功
                //.....
                that.getOrderList();
              }
              if (props.referrerInfo.extraData.payStatus === '3') {
                console.log('用户取消支付')
                //用户取消支付(订单状态流转为已关闭)
                //......
                wx.showModal({
                  content: '付款失败',
                  showCancel: false,
                  confirmText: '我知道了',
                  confirmColor: '#ff5151',
                  success(e) {
                    if (e.confirm) {
                      that.getOrderList();
                    }
                  }
                })
              }
              console.log(123)
              if (listener) {
                console.log(456)
                wx.offAppShow(listener)
              }
            };
            wx.onAppShow(listener)
          },
          fail(e) {
            console.log(e, 999999)
            // 打开失败
          },
        })
      } else {
        wx.showModal({
          content: res.msg,
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {
            that.getOrderList();
          }
        })
      }
    })
  },
  onHide() {
    const that = this;
    that.setData({
      hiddenLoading: true
    })
  },
  /**
   * 隐藏模态对话框
   */
  hideModal() {
    this.setData({
      showModal: false
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel() {
    this.hideModal();
  },
  /**
   * 对话框确认按钮点击事件
   */
  onConfirm: function () {
    this.hideModal();
    this.doPay();
  },

  choose(e) {
    var index = e.currentTarget.dataset.index
    var value = e.currentTarget.dataset.name
    console.log(value, index)
    this.setData({
      curindex: index
    })
  }
})